import { $cForm } from '../../../utils/index'

Page({
  data: {
    checkbox: ['1'],
    radio: '1',
    switch: true,
    disabled: false,
    countryCodes: ["+86", "+80", "+84", "+87"],
    countryCodeIndex: 0,

    countries: ["中国", "美国", "英国"],
    countryIndex: 0,
    date: "2016-09-01",
    time: "12:01",
    accounts: ["微信号", "QQ", "Email"],
    accountIndex: 0,
    isAgree: false
  },
  onCheckboxChange(e) {
    const { value } = e.detail
    const data = this.data.checkbox
    const index = data.indexOf(value)
    const checkbox = index === -1 ? [...data, value] : data.filter((n) => n !== value)

    this.setData({ checkbox })
  },
  onRadioChange(e) {
    this.setData({ radio: e.detail.value })
  },
  onSwitchChange(e) {
    this.setData({ switch: e.detail.value })
  },
  formSubmit(e) {
    console.log('Default Form Submit \n', e.detail.value)
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  bindCountryCodeChange: function (e) {
    console.log('picker country code 发生选择改变，携带值为', e.detail.value);

    this.setData({
      countryCodeIndex: e.detail.value
    })
  },
  bindCountryChange: function (e) {
    console.log('picker country 发生选择改变，携带值为', e.detail.value);

    this.setData({
      countryIndex: e.detail.value
    })
  },
  bindAccountChange: function (e) {
    console.log('picker account 发生选择改变，携带值为', e.detail.value);

    this.setData({
      accountIndex: e.detail.value
    })
  },
  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },
  onSubmit() {
    const { getFieldsValue, getFieldValue, setFieldsValue } = $cForm()
    const value = getFieldsValue()

    console.log('c Form Submit \n', value)
  },
  onChange(e) {
    const { form, changedValues, allValues } = e.detail

    console.log('onChange \n', changedValues, allValues)
  },
  onReset() {
    const { getFieldsValue, setFieldsValue } = $cForm()
    const fields = getFieldsValue()

    for (let item in fields) {
      if ({}.hasOwnProperty.call(fields, item)) {
        if (Array.isArray(fields[item])) {
          fields[item] = []
          if (item === 'slider') {
            fields[item] = [10, 80]
          }
        } else if (typeof fields[item] === 'boolean') {
          fields[item] = false
        } else if (typeof fields[item] === 'number') {
          fields[item] = 0
        } else {
          fields[item] = ''
        }
      }
    }

    setFieldsValue({
      ...fields,
    })
  },
})
